import React, { useState } from 'react';
import { ProFormColumnsType } from '@ant-design/pro-components';
import SchemaForm from '@/components/SchemaForm';
import { schema } from '@/ts/base';
import UploadItem from '../../tools/uploadItem';
import type { IReportTree } from '@/ts/core/thing/standard/reporttree';
import { allNodeTypes } from '@/ts/core/thing/standard/reporttree/consts';
import SearchTargetItem from '@/components/DataStandard/WorkForm/Viewer/customItem/searchTarget';
import { ISpecies, TargetType } from '@/ts/core';
import { SpeciesItemSelect } from './SpeciesItemSelect';
import { Radio, Row } from 'antd';
import { EntityInput } from '@/components/Common/EntityInput';
import { generateShortUuid } from '@/ts/base/common/uuid';

interface Iprops {
  open: boolean;
  typeName: string;
  operateType: string;
  data?: schema.XReportTreeNode;
  handleCancel: () => void;
  handleOk: (success: boolean) => void;
  current: IReportTree;
  externalField?: any;
}
/*
  字典子项编辑模态框
*/
const ReportTreeNodeModal = ({
  open,
  typeName,
  operateType,
  handleOk,
  current,
  data,
  handleCancel,
  externalField,
}: Iprops) => {
  const [selectType, setSelectType] = useState(1);
  const [speciesId, setSpeciesId] = useState('');
  const [species, setSpecies] = useState<ISpecies | null>(null!);

  const treeData = operateType === 'add' && data ? [data] : current.nodes;
  const title =
    operateType == 'add'
      ? data
        ? `新增[${data.name}]的子${typeName}节点`
        : `新增${typeName}节点`
      : `编辑[${data?.name}]${typeName}节点`;
  const initialValue = operateType === 'edit' ? data : {};
  const columns: ProFormColumnsType<schema.XReportTreeNode>[] = [
    {
      title: '图标',
      dataIndex: 'icon',
      colProps: { span: 24 },
      renderFormItem: (_, __, form) => {
        return (
          <UploadItem
            typeName={typeName}
            icon={data?.icon || ''}
            onChanged={(icon) => {
              form.setFieldValue('icon', icon);
            }}
            directory={current.directory}
          />
        );
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
      formItemProps: {
        rules: [{ required: true, message: typeName + '节点名称为必填项' }],
      },
    },
    {
      title: '代码',
      dataIndex: 'code',
      formItemProps: {
        rules: [{ required: true, message: '报表树节点代码为必填项' }],
      },
    },
    {
      title: '节点类型',
      dataIndex: 'nodeTypeName',
      valueType: 'select',
      fieldProps: {
        options: allNodeTypes.map((value) => ({
          value,
          label: value,
        })),
      },
      formItemProps: {
        rules: [{ required: true, message: '节点类型为必填项' }],
      },
    },
    {
      title: '上级节点',
      dataIndex: 'parentId',
      valueType: 'treeSelect',
      fieldProps: {
        treeDefaultExpandAll: true,
        treeData: treeData.map((node) => ({
          title: node.name,
          value: node.id,
          key: node.id,
          children: [],
        })),
        placeholder: '请选择上级节点',
        value: operateType === 'add' ? data?.id : data?.parentId,
        disabled: operateType === 'add',
      },
      formItemProps: {
        rules:
          operateType === 'add' ? [] : [{ required: true, message: '上级节点为必填项' }],
      },
    },
    {
      title: '变更关联组织',
      dataIndex: 'targetId',
      colProps: { span: 24 },
      renderFormItem: (_, __, form) => {
        return (
          <>
            <div className="flex flex-col" style={{ gap: '16px' }}>
              <div>变更关联组织会影响数据查询</div>
              <div>选择方式：</div>
              <Radio.Group
                value={selectType}
                onChange={(e) => setSelectType(e.target.value)}>
                <Radio value={1}>单位</Radio>
                <Radio value={3}>集群</Radio>
                <Radio value={2}>分类</Radio>
              </Radio.Group>
              {selectType == 1 && (
                <SearchTargetItem
                  style={{ width: '100%' }}
                  value={operateType == 'add' ? '' : data?.targetId}
                  typeName={TargetType.Company}
                  onValueChanged={(e) => form.setFieldValue('targetId', e.value)}
                />
              )}
              {selectType == 3 && (
                <SearchTargetItem
                  style={{ width: '100%' }}
                  value={operateType == 'add' ? '' : data?.targetId}
                  typeName={TargetType.Group}
                  onValueChanged={(e) => form.setFieldValue('targetId', e.value)}
                />
              )}
              {selectType == 2 && (
                <>
                  <Row>
                    <div>选择分类：</div>
                    <EntityInput
                      typeName="分类"
                      directory={current.directory}
                      value={speciesId}
                      onChange={() => {}}
                      onValueChange={(file) => {
                        setSpecies(file as ISpecies);
                        setSpeciesId(file.id);
                      }}
                    />
                  </Row>
                  {species && (
                    <Row>
                      <div>分类项：</div>
                      <SpeciesItemSelect
                        species={species}
                        value={operateType == 'add' ? '' : form.getFieldValue('targetId')}
                        onChange={(v) => {
                          form.setFieldValue('targetId', v);
                        }}
                      />
                    </Row>
                  )}
                </>
              )}
            </div>
          </>
        );
      },
    },
    {
      title: '变更归属组织',
      dataIndex: 'belongId',
      colProps: { span: 24 },
      renderFormItem: (_, __, form) => {
        return (
          <SearchTargetItem
            style={{ width: '100%' }}
            value={operateType == 'add' ? '' : data?.belongId}
            typeName={TargetType.Company}
            onValueChanged={(e) => form.setFieldValue('belongId', e.value)}
          />
        );
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      colProps: { span: 24 },
    },
  ].filter(Boolean); // 使用filter(Boolean)来去除undefined项

  return (
    <SchemaForm<schema.XReportTreeNode>
      title={title}
      open={open}
      width={640}
      columns={columns}
      layoutType="ModalForm"
      initialValues={initialValue}
      onOpenChange={(open: boolean) => {
        if (!open) {
          handleCancel();
        }
      }}
      rowProps={{
        gutter: [24, 0],
      }}
      onFinish={async (values) => {
        if (operateType == 'edit') {
          handleOk(await current.updateNode(data!, { ...data, ...values }));
        } else {
          if (data) {
            values.parentId = data.id;
            let uuid = generateShortUuid();
            values.nodePath = data.nodePath + '/' + uuid;
            values.id = uuid;
          }
          if (externalField) {
            values = { ...values, ...externalField };
          }
          handleOk((await current.createNode(values)) != undefined);
        }
      }}
    />
  );
};

export default ReportTreeNodeModal;
